﻿namespace _29两数相除
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
    public class Solution
    {
        public int Divide(int dividend, int divisor)
        {
            int MAX_INT = 2147483647;  // 2^31 - 1
            int MIN_INT = -2147483648; // -2^31

            // 处理符号
            bool sign = (dividend > 0) ^ (divisor > 0);
            long absDividend = Math.Abs((long)dividend);
            long absDivisor = Math.Abs((long)divisor);

            long quotient = 0;
            while (absDividend >= absDivisor)
            {
                long currentQuotient = 1;
                long currentDivisor = absDivisor;

                while (currentDivisor << 1 <= absDividend)
                {
                    currentQuotient <<= 1;
                    currentDivisor <<= 1;
                }

                absDividend -= currentDivisor;
                quotient += currentQuotient;
            }

            if (sign)
            {
                quotient = -quotient;
            }

            if (quotient > MAX_INT)
            {
                return MAX_INT;
            }
            else if (quotient < MIN_INT)
            {
                return MIN_INT;
            }
            else
            {
                return (int)quotient;
            }
        }
    }
}